// pages/healthData/healthData.js
import * as echarts from '../../ec-canvas/echarts';
import {getAge} from '../../utils/getAge';
import {getBody18,GetFatModel,getBodyIndex,AddFatDetail,GetFatDetailList,UpdateFat,GetLastFatDetail,tzcBindDevice} from '../../api/api';
import {visceralFatJudge,basalMetabolismJudge,proteinJudge,bmiJudge,pbfJudge,muscleJudge,boneJudge,ageJudge,waterJudge} from "../../utils/levelTool";
import {getCurrentDate} from '../../utils/timeTool';
import {setOptionMeter,setOptionLine} from '../../utils/visualTable';
import getNextDate from '../../utils/getNextDate';
import {
  addDevice,
  addEventListener,
  isBluetoothAvailable,
  removeDevice,
  startDeviceSync,
  stopDeviceSync,
  scanDevice,
  stopScan,
  initManager,
  cancelDeviceBinding,
  bindDevice
} from "../DeviceMananer";
var LSBluetoothPlugin = requirePlugin("LSDevicePlugin");
var onBindingListener = null;//new OnBindingListener();
var onSettingListener = null;//new OnSettingListener();
const TEXTS=['待连接', '正在搜索...', '底层已连接', '扫描失败请重启蓝牙', '请上秤测量','正在搜索...'];

// 获取身高
const userheight = []

for (let i = 140; i <= 200; i++) {
  userheight.push(i)
}
const userBirth = []

for (let i = 140; i <= 200; i++) {
  userBirth.push(i)
}



Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec1: {
      lazyLoad: true
    },
    ec2:{
      lazyLoad: true
    },
    ec1isShow:false,
    ec2isShow:false,
    myWeight:0,
    lineData:{
        // date:['04/14', '04/15', '04/16', '04/17', '04/18', '04/19', '04/20'],
        // weight:[140,70, 65, 62, 78, 80, 63.3],
        // bodyFat:[12, 14, 6, 14, 25, 13, 15.8]
    },
    // 出生年月
    isShowBirth:false,
    years: [],
    months: [],
    days: [],
    dateIndex:[],
    year: "",
    month: "",
    day: "",
    birthValue:[],
    // 身高
    userheight: userheight,
    heightValue:["20"],
    currentHeightValue:160,
    userHeightValue:"160",
    isShowHeight:false,
    //性别
    userSex:1,
    //控制底部弹框 显示和隐藏
    bottomBoxShow:false,
    //秤的数据

    deviceMac:"",
    deviceName:"",
    connectId:"",
    statusMsg: '请打开蓝牙', //蓝牙链接状态
    isBluetoothEnable: false,
    isScanning: true,
    isSelected: false,
    isScanCancel: false,
    scanResults: [{
      name: '',
      broadcastId: '',
      connectId:''
    }],
    // 秤图标的显示和隐藏
    chengIconShow:false,
    //获取数据的值
      bodyFatDatasAge:0,
      bodyFatDatasSex:1,//默认为男
      bodyFatDatasWeight:0,
      bodyFatDatasHeight:0,
      bodyFatDatasResistance:0,
      bodyFatDatasId:0,
    //请求体脂18api接口获取的数据
    bodyData:{
      bmi:0,
      pbf:0
    },
    // 是否是达标
    compliance:{
      bmi:{
        standard:false,
        level:""
      },//体质指数，bmi
      pbf:{
        standard:false,
        level:""
      },//脂肪率， %
    },
    //手机号码
    myTel:"",
    //登录有的用户信息  用于首次获取用户信息
    TZCuserInfo:{},
    isDeviceBinding: false,
    randomNumber: '',
    // showRandomNumInput:""
    bindscanResult:{},
    isWeighing:false,//是否能秤重，
    // 传给查看分析的参数
    currentDataParameter:{}
  },
  //性别
  toggleSex(e){
    let sexIndex=e.currentTarget.dataset.sex;
    this.setData({
      userSex:sexIndex
    })
},


  //身高
  bindChangeHeight: function (e) {
    const val = e.detail.value
    this.setData({
      currentHeightValue: val[0]+140,
    })
  },
  // 显示身高弹框
  showHeight(){
    this.setData({
      isShowHeight:true,
      heightValue:[this.data.userHeightValue-140]
    })

  },
  hiddenHeight(){
    this.setData({
      isShowHeight:false
    })
  },
  saveHeight(){
    let {currentHeightValue}=this.data;
    this.setData({
      userHeightValue:currentHeightValue
    })
    this.hiddenHeight();
  },


   // 出生年月
   bindChangeBirth: function (e) {
    const val = e.detail.value
    this.setData({
      currentBirthValue: val[0]+140,
    })
  },
  showBirth(){
    this.setData({
      isShowBirth:true,
      BirthValue:[this.data.userBirthValue-140]
    })

  },
  hiddenBirth(){
    this.setData({
      isShowBirth:false
    })
  },
  // 获取当前月份的天数
  mGetDate(year, month){
    var d = new Date(year, month, 0);
    return d.getDate();
  },
  saveBirth(){
    let {dateIndex,years,months,days}=this.data;
    this.setData({
        year:years[dateIndex[0]],
        month:months[dateIndex[1]],
        day:days[dateIndex[2]],
        birthValue:dateIndex
    })
    this.hiddenBirth();
  },
  changeDate(e){
    const val = e.detail.value;
      this.setData({
        dateIndex:val
      })
      this.getDays(this.data.years[val[0]],this.data.months[val[1]]);
  },
  // 获取天数
  getDays(year,month){
    const days = [];
    for (let i = 1; i <= this.mGetDate(year,month); i++) {
      days.push(i)
    }
    this.setData({
      days
    })
  },
  getDateIndex(){
        //获取对应的日期在日期数组中的索引
        let yearIndex=this.data.years.findIndex((item)=>item==this.data.year);
        let monthIndex=this.data.months.findIndex((item)=>item==this.data.month);
        let dayIndex=this.data.days.findIndex((item)=>item==this.data.day);
        let birthValue=[];
        birthValue[0]=yearIndex;
        birthValue[1]=monthIndex;
        birthValue[2]=dayIndex;
        this.setData({
          birthValue
        })
  },

  //保存用户的数据
  saveHeathData(){
    let {year,month,day,userHeightValue,userSex,TZCuserInfo}=this.data;


    let age=getAge(year,month,day);
    let height=userHeightValue/100;
    let sex=userSex;
      // let personalBodyData={
      //     age,
      //     height,
      //     sex,
      // }
      this.setData({
        bottomBoxShow:false,
        bodyFatDatasAge:age,
        bodyFatDatasSex:sex,//默认为男
        bodyFatDatasHeight:height,
      })

      let data={
        "id":TZCuserInfo.id,
        "nickname":TZCuserInfo.nickname,
        "customerid":TZCuserInfo.customerid,
        "tel":TZCuserInfo.tel,
        "sex":sex,
        "birthdate":`${year}-${month}-${day}`,
        "height":height,
        "weight":"70",
        "photo":"/photo.jpg"
        }
        wx.setStorageSync('TZCuserInfo', data);
    //保存数据
    // getStorageSync
            // 保存用户数据
          UpdateFat(data,(e)=>{
          });

  },
  //数值表
  initMeter(){
    let {myWeight}=this.data;
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOptionMeter(chart,myWeight);
      return chart;
    });
  },
  //折线图
  initLine(){
    let {lineData}=this.data;
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOptionLine(chart,lineData.date,lineData.weight,lineData.bodyFat);
      return chart;
    });
  },


  

    // 体脂秤方法
    // //发起连接请求
    connectDevice: function () {
      this.setData({
        isConnecting: true,
        connectState: 1,
      });
   
      let mac = this.data.deviceMac;
      if (mac === null || mac === undefined || mac === '') {
        //重置当前mac
        mac = this.data.connectId;
        this.setData({deviceMac: mac})
      }
      if(mac){
        addDevice({deviceName: this.data.deviceName, deviceMac: mac},(succeed,msg)=>{
          if (!succeed) {
            let tips = msg;
            if (typeof msg === 'object') {
              tips = JSON.stringify(msg);
            }
            wx.showModal({
              title:"添加设备失败",
              showCancel: false,
              content: tips,
              success: () => {
              },
            });
          }else{
            this.stopSearch();
             //注册数据同步回调
            startDeviceSync();
          }
          
        });
      }
    
     
    },
  
    //断开连接
    disconnectDevice: function () {
      this.setData({
        isConnecting: false,
        connectState: 0,
      })
      let mac = this.data.deviceMac;
      removeDevice({deviceMac: mac})
      stopDeviceSync();
    },


    //开始搜索
    startSearch: function () {
      this.updateStatusMessage('正在搜索...')
      //清除缓存
      this.setData({
        scanResults: [],
        deviceIds:[],
        isScanning: true,
        isScanCancel: false,
        
      });

      //开启扫描
    let ret= scanDevice({
        // broadcastNames:"LS212-B",
        callback: (device) => {
          console.log("搜索到的秤",device);
           if(device.id&&device.deviceName&&device.broadcastId){
            
            //  let getConnectId=wx.getStorageSync('ConnectId' + device.broadcastId);
            //  console.log("查到的数据",getConnectId);
            this.setData({
              deviceMac:device.broadcastId,
              deviceName:device.deviceName,
              connectId:device.id,
            })
            this.stopSearch();
            this.disconnectDevice();
            this.testDeviceBinding();
            // if(getConnectId){
            //   console.log("测试提示：已经连过的了");
            //   this.connectDevice();
            // }else{
            //   console.log("测试提示：没有连过 需要绑定");
            //   this.testDeviceBinding();
            // }

  
           }

           

        }
      });
    if(ret!==true){

      this.showBlueoothStatus(isBluetoothAvailable())
    }
    },

    //停止搜索
    stopSearch: function () {
      this.setData({
        scanResults: [],
        isScanning: false,
        isScanCancel: true
      });
      stopScan()
    },

    


    //显示手机当前的蓝牙状态
    showBlueoothStatus: function (enable) {
      if (enable) {
        this.setData({
          isBluetoothEnable: true,
        });
      } else {
        this.setData({
          isBluetoothEnable: false,
          statusMsg: '请打开蓝牙',
          isScanning: false
        })
      }
    },
  
    //更新界面的提示信息
    updateStatusMessage: function (msg) {
      this.setData({
        statusMsg: msg
      });
    },

  

    //折现图的数据渲染
    
  lineDataApply(){
    let fatid=this.data.TZCuserInfo.id;
    //折线图渲染
    let GetFatDetailLisDatat={
      fatid,
      startdate:getNextDate(getCurrentDate().date,-30),
      enddate:getNextDate(getCurrentDate().date,1),
    };
    GetFatDetailList(GetFatDetailLisDatat,(e)=>{
        if(e.data){
          let date=[];
            let weight=[];
            let bodyFat=[];
            e.data.forEach((val)=>{
                date.push(val.createdate.substring(5, 10));
                weight.push(val.weight);
                bodyFat.push(val.pbf);
            });
            let lineData={
              date,
              weight,
              bodyFat,
            };
            this.setData({
              lineData,
              ec2isShow:true,
            })
            this.ecComponent = this.selectComponent('#mychart-dom-line');
            this.initLine();
        }
    })
  },
            
  //数据绑定
  testDeviceBinding() {
    //断开数据同步连接
    // console.log("绑定数据");
    // wx.showLoading({
    //   title: 'binding...',
    //   icon: 'loading',
    // })
    //建立绑定连接
    // let self=this;
    let obj = {
      broadcastId: this.data.deviceMac,
      id: this.data.connectId
    }
    this.setData({
      bindscanResult:obj
    })
    //绑定的回调函数
    // let functionS={
    //   onBindingCommandUpdate:function(e){
    //     console.log(e);
    //   },
    //   onBindingResults:function(e){
    //     // console.log(e);
    //     if (e.code==200) {
    //       self.connectDevice();
    //       console.log("绑定成功");
    //     }else{
    //       console.log("绑定失败");
    //       self.updateStatusMessage("连接超时 请重启蓝牙");
    //     }
    //   }
    // }
    setTimeout(function(){
      //建立绑定连接
      LSBluetoothPlugin.bindDevice(obj, onBindingListener);
  
      // bindDevice(obj,functionS);
    },1000)


  },
  //设置成功提示
  showSuccess: function (titleMsg) {
    wx.hideLoading();
    wx.showToast({
      title: titleMsg,
      mask: true,
      icon: 'success'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    
       //获取出生日期的选项
       const date = new Date()
       const years = []
       const months = []
       let year="1990";
       let month="6";
       let day="6";
   
       for (let i = 1950; i <= date.getFullYear()-2; i++) {
         years.push(i)
       }
   
       for (let i = 1; i <= 12; i++) {
         months.push(i)
       }
   
       this.getDays(year,month);
   
       this.setData({
         years,
         months,
         year,
         month,
         day,
       })
        this.getDateIndex();

      
       


     

      let self=this;
        //注册蓝牙连接监听
        addEventListener("bluetoothStateChange", (res) => {
          if(res.available){
            this.updateStatusMessage('蓝牙准备中...');
              initManager(res=>{
                if(res){
                  console.log("搜索1");
                      this.startSearch();
                    }
                })
          }else{
            this.updateStatusMessage('请打开蓝牙');
            this.stopSearch();
            this.disconnectDevice();
          }
        });
          //注册设备连接监听
        addEventListener("connectionStateChange", (device) => {
            if(device){
            self.setData({statusMsg: TEXTS[device.status]})
            self.setData({connectState: device.status});
            }
  
        });
  
        //注册数据回调监听
        addEventListener('dataChanged',
        (deviceMac, dataType, data, dataStr) => {
          let timestamp=Date.parse(new Date());
          // console.log("时间戳",timestamp);//1628243836000
          // console.log("数据变化",data);   //1628243835
          // console.log("判断是否是最近的数据",timestamp-(data.utc*1000)<10000)
          // if (data.remainCount==0) {
            // 离开页面  停止秤重
            if (this.data.isWeighing) {
              return;
            }
          // 判断是否是最近的10秒的秤重记录
          if (data.remainCount==0&&timestamp-(data.utc*1000)<10000) {
            let {bodyFatDatasAge,bodyFatDatasSex,bodyFatDatasHeight,bodyFatDatasId}=this.data;
            let myWeight=data.weight||0;
            if(myWeight<10){
              wx.showModal({
                title: '体重过轻',
                content: '体重不能低于10kg',
                showCancel:false,
                success (res) {
                  
                }
              })
              return;
            }
            if(myWeight){
              myWeight=myWeight.toFixed(1)
            }
            let resistance=data.resistance;
            let that=this;
            let TZCphone=wx.getStorageSync('TZCphone');
            if(!TZCphone){
                     wx.showToast({
  
                      title: '获取身体数据失败 请先登录',
                
                      icon: 'none',
                
                      duration: 2000//持续的时间
                
                    })
              return;
            }
            if(!resistance){
              if(myWeight){
                wx.showModal({
                  title: '没有体脂数据',
                  content: '请光脚站在体脂秤测量。忽略体脂数据，仅保存体重数据？',
                  cancelText:'重新测试',
                  confirmText:'保存',
                  success (res) {
                    if (res.confirm) {
                      //获取请求的值
                      let data={
                        age:bodyFatDatasAge,
                        sex:bodyFatDatasSex,
                        weight:myWeight,
                        height:bodyFatDatasHeight,
                        resistance:resistance
                      };
                      console.log(data);
                      getBody18(data,(e)=>{
                        let bodyData=e.data.data;
                        // console.log("bodyData+++++++",bodyData);
                        let bmi=bmiJudge(bodyData.bmi);
                        console.log(bmi);
                        bodyData.fatid=bodyFatDatasId;
                        bodyData.bmiName=bmi.level+'.'+bmi.standard;
                        if(bodyData){
                          AddFatDetail(bodyData,(e)=>{  
                            that.lineDataApply();
                          });
                          
                                                // 判断值在哪个范围内
                        let compliance={
                          bmi:bmi,
                        }
                        //缓存数据
                        let TZCcacheData={
                          compliance,
                          bodyData,
                          weight:myWeight
                        }
                        //保存体重的数据
                        let myWeights=wx.getStorageSync('myWeights');
                        if(myWeights){
                          myWeights.unshift(myWeight);
                        }else{
                          myWeights=[myWeight];
                        }
                        wx.setStorageSync('myWeights', myWeights);
                        wx.setStorageSync('TZCcacheData', TZCcacheData);
                        that.setData({
                            bodyData,
                            compliance,
                            myWeight,
                            ec1isShow:true
                          })
                          // 保存数据到分析页面
                          let analyzeDataStorageSync={
                              weight:myWeight,
                              bodyData,
                              currentTime:getCurrentDate(),
                          }
                          wx.setStorageSync('myDataStorageSync',data);
                          wx.setStorageSync('analyzeDataStorageSync',analyzeDataStorageSync);
                          that.ecComponent = that.selectComponent('#mychart-dom-gauge');
                          that.initMeter();
      
                        }
      
                      })
      
                    } else if (res.cancel) {
                    }
                  }
                })
              }
    
            }else{
                //添加个提示
                // 测试完成
                wx.showToast({
                  title: '测量完成',
                  icon: 'none',
                  duration: 3000//持续的时间
                })
                  //获取到电阻数据
                  let data={
                    age:bodyFatDatasAge,
                    sex:bodyFatDatasSex,
                    weight:myWeight,
                    height:bodyFatDatasHeight,
                    resistance:resistance
                  };
                  getBody18(data,(e)=>{
                    let bodyData=e.data.data;
                      console.log(data);
                      getBodyIndex(data,(e)=>{
                        let getBodyIndexData=e.data.data.labelList; 
                        console.log(getBodyIndexData);
                                  // 判断值在哪个范围内
                          let bmi=bmiJudge(bodyData.bmi); 
                          let pbf=pbfJudge(bodyData.pbf,getBodyIndexData[1].levelIntervalList); 
                          let visceralFat=visceralFatJudge(bodyData.visceralFat,getBodyIndexData[5].levelIntervalList);
                          let basalMetabolism=basalMetabolismJudge(bodyData.basalMetabolism,getBodyIndexData[6].levelIntervalList)
                          let protein=proteinJudge(bodyData.protein,getBodyIndexData[11].levelIntervalList); //这个标准错误 裸脚秤下 试试范围值
                          let rateOfMuscle=muscleJudge(bodyData.rateOfMuscle,getBodyIndexData[8].levelIntervalList); 
                          let bone=boneJudge(bodyData.bone,getBodyIndexData[10].levelIntervalList); 
                          let bodyAge=ageJudge(bodyData.age,bodyData.bodyAge,bodyData.basalMetabolism); 
                          let water=waterJudge(bodyData.water,getBodyIndexData[9].levelIntervalList); 
                          // 添加到后台的文本数据0 1  5 6 11 8 10 4 9
                          // labelContent
                          // labelDietaryAdvice
                          // labelSportsAdvice

                          let compliance={
                            bmi:bmi,
                            pbf:pbf,
                          }
                          if(bodyData){
                            bodyData.fatid=bodyFatDatasId;
                            bodyData.bmiName=bmi.level+'#'+bmi.standard+'#'+getBodyIndexData[0].labelContent+'#'+getBodyIndexData[0].labelDietaryAdvice+'#'+getBodyIndexData[0].labelSportsAdvice;

                            bodyData.pbfName=pbf.level+'#'+pbf.standard+'#'+getBodyIndexData[1].labelContent+'#'+getBodyIndexData[1].labelDietaryAdvice+'#'+getBodyIndexData[1].labelSportsAdvice;

                            bodyData.visceralFatName=visceralFat.level+'#'+visceralFat.standard+'#'+getBodyIndexData[5].labelContent+'#'+getBodyIndexData[5].labelDietaryAdvice+'#'+getBodyIndexData[5].labelSportsAdvice;

                            bodyData.basalMetabolismName=basalMetabolism.level+'#'+basalMetabolism.standard+'#'+getBodyIndexData[6].labelContent+'#'+getBodyIndexData[6].labelDietaryAdvice+'#'+getBodyIndexData[6].labelSportsAdvice;

                            bodyData.proteinName=protein.level+'#'+protein.standard+'#'+getBodyIndexData[11].labelContent+'#'+getBodyIndexData[11].labelDietaryAdvice+'#'+getBodyIndexData[11].labelSportsAdvice;

                            bodyData.rateOfMuscleName=rateOfMuscle.level+'#'+rateOfMuscle.standard+'#'+getBodyIndexData[8].labelContent+'#'+getBodyIndexData[8].labelDietaryAdvice+'#'+getBodyIndexData[8].labelSportsAdvice;

                            
                            bodyData.boneName=bone.level+'#'+bone.standard+'#'+getBodyIndexData[10].labelContent+'#'+getBodyIndexData[10].labelDietaryAdvice+'#'+getBodyIndexData[10].labelSportsAdvice;


                            bodyData.bodyAgeName=bodyAge.level+'#'+bodyAge.standard+'#'+getBodyIndexData[3].labelContent+'#'+getBodyIndexData[3].labelDietaryAdvice+'#'+getBodyIndexData[3].labelSportsAdvice;


                            bodyData.waterName=water.level+'#'+water.standard+'#'+getBodyIndexData[9].labelContent+'#'+getBodyIndexData[9].labelDietaryAdvice+'#'+getBodyIndexData[9].labelSportsAdvice;

                        
                      

                            //       bmiName:data.bmiName,
                            //       pbfName:data.pbfName,
                            //       basalMetabolismName:data.basalMetabolismName,
                            //       bodyAgeName:data.bodyAgeName,
                            //       visceralFatName:data.visceralFatName,
                            //       waterName:data.waterName,
                            //       boneName:data.boneName,
                            //       proteinName:data.proteinName,
                            //       rateOfMuscleName:data.rateOfMuscleName
                            console.log(bodyData);
                            AddFatDetail(bodyData,(e)=>{  
                              that.lineDataApply();
                            });
                         }


                          //缓存数据
                        //缓存数据
                          let TZCcacheData={
                            compliance,
                            bodyData,
                            weight:myWeight
                          }
                          //保存体重的数据
                          let myWeights=wx.getStorageSync('myWeights');
                          if(myWeights){
                            myWeights.unshift(myWeight);
                          }else{
                            myWeights=[myWeight];
                          }
                          wx.setStorageSync('myWeights', myWeights);
                          wx.setStorageSync('TZCcacheData', TZCcacheData);
                          that.setData({
                              bodyData,
                              compliance,
                              myWeight,
                              ec1isShow:true
                            })
                            // 保存数据到分析页面
                            let analyzeDataStorageSync={
                                weight:myWeight,
                                bodyData,
                                getIndexData:data,
                                currentTime:getCurrentDate()
                            }
                    
                            wx.setStorageSync('analyzeDataStorageSync',analyzeDataStorageSync);
                            that.ecComponent = that.selectComponent('#mychart-dom-gauge');
                            that.initMeter();
                        })
                  
    
    
                  })
    
    
    
            }
    
          }
       
  
        })
          


 


  





  },
  //渲染折线图
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // let TZCphone=wx.getStorageSync('TZCphone');
    //sdk 初始化
    // initManager(res=>{
    // if(res){
    //     }
    // })
    let self = this;
    // //判断手机蓝牙是否可用
    if (isBluetoothAvailable()) {
      console.log("搜索0");
      this.startSearch();
    } else {
    }

    onSettingListener = {
      onSuccess: function () {
        console.log('UI OnSettingListener.success');
        if (!self.data.isDeviceBinding) {
          // self.showSuccess('设置成功');
        }
      },
      onFailure: function (msg) {
        console.log('UI OnSettingListener.failure', msg);
        // self.showFailure();
      }
    }
                      /**
     * 注册绑定回调
     */
  onBindingListener = {
    // 链接状态的变化
    onConnectionStateChanged: function (deviceMac, state) {
      console.log("当前状态",state);
      console.log(
        `[Device Manager] Connection state change: Mac = ${deviceMac} Status = ${status}`);
    },
    //绑定更新
    onBindingCommandUpdate: function (deviceMac, bindCmd) {
      if (bindCmd === LSBluetoothPlugin.Profiles.BindingCmd.InputRandomNumber) {

      }
      else if (bindCmd === LSBluetoothPlugin.Profiles.BindingCmd.RegisterDeviceID) {

        //注册设备ID
        let id = deviceMac;//mac.replace(/:/g, '')
        console.log("设备id",id);
        let idSetting = new LSBluetoothPlugin.SettingProfile.RegisterIdSetting(id);
        // console.log("idSetting..................",idSetting);
        LSBluetoothPlugin.pushSettings(deviceMac, idSetting, onSettingListener);
      }
    },
    // 绑定结果
    onBindingResults: function (deviceInfo, status) {
      //取消绑定
      // cancelDeviceBinding(self.data.bindscanResult);
      if (status) {
        // console.log('绑定的数据', deviceInfo);
        //用于绑定设备 但api无法调用
        // tzcBindDevice(deviceInfo.id,(e)=>{
        //   console.log(e);
        // });

        //绑定成功
        console.log("绑定成功");
        self.connectDevice();
        self.setData({
          isDeviceBinding: false,
        })
      }
      else {
        //绑定失败
        console.log("绑定失败");
        self.updateStatusMessage("连接失败 请重启蓝牙");
        self.setData({
          isDeviceBinding: false,
        })

      }
    }
  }


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isWeighing:false
    })
    //获取登录后的用户信息
    let TZCuserInfo=wx.getStorageSync("TZCuserInfo");
    this.setData({
      TZCuserInfo,
    })


     //用于获取最近的数据
     if (TZCuserInfo) {
      wx.showLoading({
        title: '加载中',
        mask:true
      })
        // //获取最近的数据
        // let getFatDetailListData={
        //   fatid: TZCuserInfo.id,
        //   startdate:getNextDate(getCurrentDate().date,-30),
        //   enddate: getNextDate(getCurrentDate().date,1),
        // }
        GetLastFatDetail(TZCuserInfo.id,(e)=>{
          if (e.data) {
            let currentData= e.data;
            let currentDataParameter=JSON.stringify(currentData);
            this.setData({
              currentDataParameter
            })
            let bmi=bmiJudge(currentData.bmi); 
            let pbf={}
            let getBodyIndexRequestData={
              weight:currentData.weight,
              age:currentData.age,
              sex:currentData.sex,
              height:currentData.height,
              resistance:currentData.resistance50k
            }
            getBodyIndex(getBodyIndexRequestData,(e)=>{
              // console.log(e)//阻抗值必须大于10！
              // console.log(e.data);
              if(!e.data.data){
                return;
              }
              if(e.data.data.labelList){
                let getBodyIndexData=e.data.data.labelList;
                if (getBodyIndexData[1]) {
                  pbf=pbfJudge(currentData.pbf,getBodyIndexData[1].levelIntervalList); 
                }else{
                  pbf={
                    standard:false,
                    level:""
                  }
                }
                let compliance={
                  bmi,
                  pbf
                }
                this.setData({
                  compliance
                })
              }
                
                // console.log(getBodyIndexData);

            })
    
            let bodyData={
              bmi:currentData.bmi,
              pbf:currentData.pbf
            }
            this.setData({
              myWeight:currentData.weight,
              ec1isShow:true,
              bodyData,
            })
          this.ecComponent = this.selectComponent('#mychart-dom-gauge');
          this.initMeter();
          }
          wx.hideLoading();

        })
       
     }

          
    let TZCphone=wx.getStorageSync('TZCphone');
    let openid=wx.getStorageSync('TZCopenid');
    if (!openid) {
      openid=""
    }
      if(!TZCphone){
        wx.showModal({
          title: '提示',
          content: '你还没登录，请先登录',
          showCancel:false,
          success (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '../my/my'
              })
            } 
          }
        })
        return;
      }else{
        // this.updateStatusMessage('请先登录');
        this.setData({
          myTel:TZCphone,

        })
        let getdata={
          phone:TZCphone,
          openid:openid
        }
        // //判断有没有个人信息的数据
        GetFatModel(getdata,(e)=>{
          if(e.data.birthdate&&e.data.sex&&e.data.height){
            let ageData=e.data.birthdate.substring(0,10).split("-");
            let age=getAge(ageData[0],ageData[1],ageData[2])
            this.setData({
                bottomBoxShow:false,
                bodyFatDatasAge:age,
                bodyFatDatasSex:e.data.sex,
                bodyFatDatasHeight:e.data.height,
                bodyFatDatasId:e.data.id
            })  
            this.lineDataApply();
          }else{
            this.setData({
              bottomBoxShow:true
            })
          }
          


        })
        





      }
  },
    /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      isWeighing:true
    })
  },
})